// src/main/java/com/example/filters/AuthenticationFilter.java
package main.java.com.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//过滤器 前台
@WebFilter("/front/*")
public class AuthenticationTwoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        String loginURI = request.getContextPath() + "/front/login.jsp";
        boolean loggedIn = session != null && session.getAttribute("qtuser") != null;
        boolean loginRequest = request.getRequestURI().equals(loginURI);

        // 放行静态资源
        String[] uris = {".jpg",".png",".jpeg","/front/recruitment.jsp","/front/concerning.jsp","/front/merchant-center.jsp"};
        for (String uri : uris) {
            if (request.getRequestURI().endsWith(uri)) {
                chain.doFilter(request, response);
                return;
            }
        }

        //登录成功放行
        if (loggedIn || loginRequest || request.getRequestURI().endsWith("login")) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(loginURI);
        }
    }

    @Override
    public void destroy() {

    }

    // init and destroy methods
    // ...
}